package com.cjlgb.design.common.core.handler;

import com.cjlgb.design.common.core.bean.ResultBean;
import com.cjlgb.design.common.core.constant.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.concurrent.TimeoutException;

/**
 * @author WFT
 * @date 2019/5/18
 * description:全局异常处理器
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获运行时异常
     * @param e java.lang.RuntimeException
     * @return ResultBean
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseStatus(value = org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultBean runTimeException(RuntimeException e){
        log.error(e.getMessage(),e);
        return ResultBean.error(e.getMessage());
    }

    /**
     * 捕获断言异常
     * @param e java.lang.IllegalArgumentException
     * @return ResultBean
     */
    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseStatus(value = org.springframework.http.HttpStatus.BAD_REQUEST)
    public ResultBean assertionError(IllegalArgumentException e){
        return ResultBean.badRequest(e.getMessage());
    }

    /**
     * 捕获请求超时异常
     * @param e java.util.concurrent.TimeoutException
     * @return ResultBean
     */
    @ResponseBody
    @ExceptionHandler(value = TimeoutException.class)
    @ResponseStatus(value = org.springframework.http.HttpStatus.REQUEST_TIMEOUT)
    public ResultBean timeoutException(RuntimeException e){
        log.error(e.getMessage(),e);
        return ResultBean.build(HttpStatus.REQUEST_TIMEOUT,e.getMessage());
    }

    /**
     * 捕获403异常
     * @param e org.springframework.security.access.AccessDeniedException
     * @return ResultBean
     */
    @ResponseBody
    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseStatus(value = org.springframework.http.HttpStatus.FORBIDDEN)
    public ResultBean accessDeniedException(AccessDeniedException e){
        return ResultBean.build(HttpStatus.FORBIDDEN,e.getMessage());
    }

}
